package com.bds.portal.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.dao.impl.NutDao;
import org.nutz.dao.pager.Pager;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.sql.Sql;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.aliyun.openservices.ons.api.SendResult;
import com.bds.model.Hosts;
import com.bds.model.Result;
import com.bds.model.TRegin;
import com.bds.model.Template;
import com.bds.model.TemplateDetail;
import com.bds.model.TemplateUrl;
import com.bds.model.Tresult;
import com.bds.portal.common.result.Page;
import com.bds.portal.queue.TcpUrlProducer;
import com.bds.portal.util.Const;
import com.bds.portal.util.MD5Util;

@Component
public class MyService {

	private static Logger logger = Logger.getLogger(MyService.class);

	@Resource
	private NutDao portalDao;
	@Resource
	private MyTUrlService myTUrlService;
	@Resource
	private PortalService portalService;

	public List<TRegin> getReginByLevel(int level) {
		List<TRegin> list = portalDao.query(TRegin.class, Cnd.where("leveltype", "=", level));
		return list;
	}

	public Page getMyTmpData(Long user_id, String request_id, Integer pageNum, Integer pageSize) {
		Pager pager = portalDao.createPager(pageNum, pageSize);
		Criteria cri = Cnd.cri();
		cri.where().andEquals("user_id", user_id);
		cri.where().andEquals("request_id", request_id);

		List<Tresult> list = portalDao.query(Tresult.class, cri, pager);
		JSONArray array = new JSONArray();
		int count = portalDao.count(Tresult.class, cri);

		for (Tresult t : list) {
			JSONObject obj = new JSONObject();
			if (t.getResult() != null) {
				obj = JSONObject.parseObject(t.getResult());
			}
			TemplateUrl turl = portalDao.fetch(TemplateUrl.class, Cnd.where("id", "=", t.getUrl_id()));
			obj.put("#url", turl.getUrl());
			obj.put("id", t.getId());
			array.add(obj);
		}
		Page p = new Page(count, pager.getPageNumber(), pager.getPageSize());

		p.setCode(Const.SUC);
		p.setData(array);
		return p;

	}

	public List<TRegin> getReginByPid(String pid) {
		List<TRegin> list = portalDao.query(TRegin.class, Cnd.where("parentid", "=", pid));
		return list;
	}

	public List<TemplateDetail> getTemplateDetailList(String request_id) {
		List<TemplateDetail> list = portalDao.query(TemplateDetail.class, Cnd.where("request_id", "=", request_id));
		return list;
	}

	public TemplateDetail getTemplateDetailById(Long id) {
		TemplateDetail detail = portalDao.fetch(TemplateDetail.class, Cnd.where("id", "=", id));
		return detail;
	}

	public Result upTempDetailOp(Long id, String op) {
		Result ret = new Result();
		portalDao.update(TemplateDetail.class, Chain.make("op", op), Cnd.where("id", "=", id));
		ret.setCode(Const.SUC);
		return ret;
	}

	public List<Template> getMyTemplateList(Long user_id, Long hid) {
		List<Template> list = new ArrayList<Template>();
		try {
			Cnd cnd = Cnd.where("user_id", "=", user_id);
			if (hid != null) {
				cnd.and("host_id", "=", hid);
			}
			list = portalDao.query(Template.class, cnd.desc("create_time"));
			for (Template tmpl : list) {
				List<TemplateUrl> tp = myTUrlService.getAllTUrl(tmpl.getRequest_id());
				StringBuffer buf = new StringBuffer();
				for (TemplateUrl t : tp) {
					buf.append(t.getUrl() + "\n");
				}
				if (buf.length() > 0) {
					buf = buf.deleteCharAt(buf.length() - 1);
				}
				tmpl.setUrls(buf.toString());

			}
		} catch (Exception e) {
			logger.info("", e);

		}
		return list;
	}

	public Page getMyConfigList(Long user_id, Integer pageNum, Integer pageSize, Long pid, Long hid) {

		try {

			Pager pager = portalDao.createPager(pageNum, pageSize);
			String querySql = "SELECT t.*,k.prid,k.id as taskid FROM t_template t,t_task k $condition and t.request_id=k.request_id order by t.create_time desc";
			Criteria cri = Cnd.cri();
			cri.where().andEquals("t.user_id", user_id);

			List<Long> hids = new ArrayList<Long>();
			if (pid != null) {
				List<Hosts> hlist = portalDao.query(Hosts.class, Cnd.where("project_id", "=", pid));
				for (Hosts h : hlist) {
					hids.add(h.getId());
				}
			}

			if (hids.size() > 0) {
				cri.where().and("t.host_id", "in", hids);
			}
			if (hid != null) {
				cri.where().andEquals("t.host_id", hid);
			}

			Sql sql = Sqls.queryEntity(querySql);
			sql.setCallback(Sqls.callback.entities());
			sql.setCondition(cri);
			sql.setEntity(portalDao.getEntity(Template.class));
			sql.setPager(pager);
			portalDao.execute(sql);

			String countSql = "SELECT count(0) FROM t_template t,t_task k $condition and t.request_id=k.request_id";
			Sql countQuery = Sqls.fetchInt(countSql.toString());
			countQuery.setCondition(cri);
			portalDao.execute(countQuery);
			int count = countQuery.getInt();
			List<Template> list = sql.getList(Template.class);

			Page p = new Page(count, pager.getPageNumber(), pager.getPageSize());
			p.setCode(Const.SUC);
			p.setData(list);

			return p;
		} catch (Exception e) {
			logger.info("", e);

		}
		return null;
	}

	public Template getTemplate(String request_id) {

		try {
			Template tlist = portalDao.fetch(Template.class, Cnd.where("request_id", "=", request_id));

			return tlist;
		} catch (Exception e) {
			logger.info("", e);

		}
		return null;
	}

	public List<Template> getAllTemplate(Long user_id) {

		try {
			List<Template> tlist = portalDao.query(Template.class, Cnd.where("user_id", "=", user_id));

			return tlist;
		} catch (Exception e) {
			logger.info("", e);

		}
		return null;
	}

	public Result addNewTmpl(Long user_id, Long pid, Long hid, String url, String tname) {
		Result result = new Result();
		List<Template> oldList = portalDao.query(Template.class,
				Cnd.where("user_id", "=", user_id).and("template_name", "=", tname));

		if (oldList != null && oldList.size() > 0) {
			result.setCode(Const.FAIL);
			result.setMsg("此模板命名已存在，请重新命名");
			return result;
		}
		SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");
		String now = fmt.format(new Date());
		String uuid = UUID.randomUUID().toString();
		String requestId = MD5Util.getMD5(uuid + url + now);
		Result ret = portalService.addTask(requestId, url, uuid, "0");
		if (ret.getCode().equals(200)) {
			Template template = new Template();
			template.setRequest_id(requestId);
			template.setTemplate_name(tname);
			template.setUser_id(user_id);
			template.setUrl(url);
			template.setHost_id(hid);
			template.setCreate_time(new Date());
			portalDao.insert(template);
			result.setResult(Const.SUC, "操作成功");
		} else {
			result.setResult(Const.FAIL, "发送url失败");
		}
		return result;

	}

	public Boolean saveTemplate(Template config, String[] urls) {
		Boolean flag = false;
		try {
			Date date = new Date();
			Template temp = portalDao.fetch(Template.class, Cnd.where("id", "=", config.getId()));
			String request_id = temp.getRequest_id();
			JSONObject json = new JSONObject();
			String[] tarry = temp.getTitle().split(",");

			List<String> tlist = new ArrayList<String>(Arrays.asList(tarry));
			String[] harry = temp.getHead().split(",");

			List<String> hlist = new ArrayList<String>(Arrays.asList(harry));
			if (StringUtils.isNotEmpty(config.getExts())) {
				String[] row = config.getExts().split(",");

				for (int i = 0; i < row.length; i++) {

					String[] ks = row[i].split("\\|");
					json.put(ks[0], ks[1]);
					String key = "ext" + i;
					if (!hlist.contains(key)) {
						hlist.add(key);
					}
					if (!tlist.contains(ks[0])) {
						tlist.add(ks[0]);
					}

				}
			}
			StringBuffer head = new StringBuffer();
			StringBuffer title = new StringBuffer();
			for (String t : tlist) {
				title = title.append(t + ",");
			}
			for (String h : hlist) {
				head = head.append(h + ",");
			}
			if (title.length() > 0) {
				title = title.deleteCharAt(title.length() - 1);
			}

			if (head.length() > 0) {
				head = head.deleteCharAt(head.length() - 1);
			}
			config.setHead(head.toString());
			config.setTitle(title.toString());
			config.setUpdate_time(date);

			portalDao.updateIgnoreNull(config);
			portalDao.clear(TemplateUrl.class, Cnd.where("request_id", "=", request_id));
			if (config.getType().equals("url") && urls != null && urls.length > 0) {
				myTUrlService.saveTUrl(config.getUser_id(), urls, request_id);
			} else {
				String prule = config.getPage_rule();

				int index = prule.indexOf("[[");
				int last = prule.indexOf("]]");

				if (index > 0 && last > 0) {
					String furl = prule.substring(0, index);
					String maxp = prule.substring(index, last + 1);
					int min = 1;
					int max = 1;
					if (maxp.split("|").length > 1) {
						String p = maxp.split("|")[0];
						String init = maxp.split("|")[1];
						min = Integer.parseInt(p.split("-")[0]);
						max = Integer.parseInt(p.split("-")[1]);
						// int b = Integer.parseInt(init.split("-")[0]);
						int e = Integer.parseInt(init);
						String lurl = prule.substring(last + 2, prule.length());
						for (int i = min; i <= max; i++) {
							String pageUlr = furl + (i * e) + lurl;
							TemplateUrl tp = new TemplateUrl();
							tp.setRequest_id(request_id);
							tp.setUser_id(config.getUser_id());
							tp.setStatus(0);
							tp.setPage(0);
							tp.setUrl(pageUlr);
							tp.setOrderby(i);
							tp.setCreate_time(new Date());
							tp.setSend_status(0);
							portalDao.fastInsert(tp);
						}
					} else {
						min = Integer.parseInt(maxp.split("-")[0]);
						max = Integer.parseInt(maxp.split("-")[1]);
						String lurl = prule.substring(last + 2, prule.length());
						for (int i = min; i <= max; i++) {
							String pageUlr = furl + i + lurl;
							TemplateUrl tp = new TemplateUrl();
							tp.setRequest_id(request_id);
							tp.setUser_id(config.getUser_id());
							tp.setStatus(0);
							tp.setPage(0);
							tp.setUrl(pageUlr);
							tp.setOrderby(i);
							tp.setCreate_time(new Date());
							tp.setSend_status(0);
							portalDao.fastInsert(tp);
						}
					}

				} else {

					TemplateUrl tp = new TemplateUrl();
					tp.setRequest_id(request_id);
					tp.setUser_id(config.getUser_id());
					tp.setStatus(0);
					tp.setPage(0);
					tp.setSend_status(0);
					tp.setUrl(config.getUrl());
					tp.setCreate_time(new Date());
					tp.setOrderby(1);
					portalDao.fastInsert(tp);

				}
			}

			flag = true;
		} catch (Exception e) {
			logger.info("", e);
		}
		return flag;
	}

	public Result doStartJob(String tid) {
		Result ret = new Result();
		try {
			Template config = portalDao.fetch(Template.class, Cnd.where("id", "=", tid));

			if (config == null || config.getType() == null || config.getType().equals("")) {
				ret.setResult(Const.FAIL, "请先保存模板");
				return ret;
			}

			List<TemplateUrl> tt = portalDao.query(TemplateUrl.class,
					Cnd.where("request_id", "=", config.getRequest_id()).and("user_id", "=", config.getUser_id()));
			for (TemplateUrl t : tt) {
//				JSONObject obj = new JSONObject();
//				obj.put("id", t.getId());
//				obj.put("requestId", t.getRequest_id());
//				obj.put("userId", t.getUser_id());
//				obj.put("table", "t_template_url");
//				obj.put("url", t.getUrl());
//				String msg = JSON.toJSONStringWithDateFormat(obj, "yyyy-MM-dd HH:mm:ss",
//						SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty,
//						SerializerFeature.WriteDateUseDateFormat);
				//SendResult send = TcpUrlProducer.getInstance().send(msg.toString(), "url");
//				if (send != null && send.getMessageId() != null) {
//					portalDao.update(TemplateUrl.class, Chain.make("send_status", 1), Cnd.where("id", "=", t.getId()));
//				} else {
					portalDao.update(TemplateUrl.class, Chain.make("send_status", 1), Cnd.where("id", "=", t.getId()));
//				}

			}

			ret.setResult(Const.SUC, "处理成功");
		} catch (Exception e) {
			logger.info("", e);
			ret.setResult(Const.FAIL, "处理异常");
		}
		return ret;
	}

	public Result repStartUrl(Long id) {
		Result ret = new Result();
		try {

			TemplateUrl t = portalDao.fetch(TemplateUrl.class, Cnd.where("id", "=", id));

//			JSONObject obj = new JSONObject();
//			obj.put("id", t.getId());
//			obj.put("requestId", t.getRequest_id());
//			obj.put("userId", t.getUser_id());
//			obj.put("table", "t_template_url");
//			obj.put("url", t.getUrl());
//			String msg = JSON.toJSONStringWithDateFormat(obj, "yyyy-MM-dd HH:mm:ss",
//					SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty,
//					SerializerFeature.WriteDateUseDateFormat);
//			SendResult send = TcpUrlProducer.getInstance().send(msg, "url");
//			if (send != null && send.getMessageId() != null) {
				portalDao.update(TemplateUrl.class, Chain.make("send_status", 1), Cnd.where("id", "=", id));
//			} else {
//				portalDao.update(TemplateUrl.class, Chain.make("send_status", 3), Cnd.where("id", "=", id));
//			}

			ret.setResult(Const.SUC, "处理成功");
		} catch (Exception e) {
			logger.info("", e);
			ret.setResult(Const.FAIL, "处理异常");
		}
		return ret;
	}

	public static void main(String[] args) {
		String url = "http://www.yanjiao.com/forum-327-[[page]].html";
		int index = url.indexOf("[[");
		int last = url.indexOf("]]");
		String furl = url.substring(0, index);

		String lurl = url.substring(last + 2, url.length());

		logger.info(furl);
		logger.info(lurl);

	}

}
